package com.mac.core.activemq;

import com.mac.core.conf.JmsConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.stereotype.Component;

import javax.jms.JMSException;
import javax.jms.Session;
import javax.jms.TextMessage;

/**
 * 消费者
 */
@Component
public class JMSConsumer {
    private final static Logger logger = LoggerFactory.getLogger(JMSConsumer.class);

    @JmsListener(destination = JmsConfig.TOPIC, containerFactory = "jmsListenerContainerTopic")
    public void onTopicMessage(final TextMessage text, Session session) {
        try {
            logger.info("接收到topic消息：{}", text.getText());
            // 使用手动签收模式，需要手动的调用，如果不在catch中调用session.recover()消息只会在重启服务后重发
            text.acknowledge();
        } catch (Exception e) {
            try {
                session.recover();// 此不可省略 重发信息使用
            } catch (JMSException e1) {
                e1.printStackTrace();
            }
        }

    }

    @JmsListener(destination = JmsConfig.QUEUE, containerFactory = "jmsListenerContainerQueue")
    public void onQueueMessage(String msg) {
        logger.info("接收到queue消息：{}",msg);
    }
}